package task

import (
	"encoding/json"
	"pids-cloud-server/constants"
	"pids-cloud-server/entity"
	"pids-cloud-server/logging"
	"pids-cloud-server/utils"
	"strings"
	"time"

	"github.com/google/uuid"
)

func HostDownTask() {
	logging.Info("----------定时检查主机掉线任务开始----------")

	// 获取数据库连接
	db := utils.GetDB()
	if db == nil {
		logging.Error("数据库连接失败，跳过主机掉线检查任务")
		return
	}

	now := time.Now()
	var systemInfos []entity.SystemInfo
	//db.Where("host_name in (?)", db.Model(&entity.SnmpInfo{}).Select("mock_ip").Where("enable = 1")).Find(&systemInfos)
	//只查询创建时间超过5分钟且当前状态为在线的主机
	cutoffTime := now.Add(-5 * time.Minute)
	db.Where("create_time < ? AND network_state = ?", cutoffTime, entity.ONLINE).Find(&systemInfos)
	if len(systemInfos) == 0 {
		logging.Info("没有需要标记为离线的主机")
		logging.Info("----------定时检查主机掉线任务结束----------")
		return
	}

	logInfoList := []entity.LogInfo{}
	var offlineIds []int64
	for _, systemInfo := range systemInfos {
		logInfo := entity.LogInfo{
			ID:          strings.ReplaceAll(uuid.NewString(), "-", ""),
			Hostname:    "主机下线：" + systemInfo.HostName,
			InfoContent: "超过5分钟未上报状态,可能已下线:" + systemInfo.HostName,
			State:       "1",
			CreateTime:  now,
		}
		logInfoList = append(logInfoList, logInfo)
		networkState := entity.NetworkState{
			ID:         utils.GenerateID().Int64(),
			CreateTime: now,
			HostName:   systemInfo.HostName,
			Status:     entity.OFFLINE,
			Type:       systemInfo.Type,
		}
		offlineIds = append(offlineIds, systemInfo.ID)
		networkstatejson, err := json.Marshal(networkState)
		if err != nil {
			logging.Error("网络状态序列化失败", err.Error())
			continue // 跳过当前主机，处理下一个
		}
		utils.LPush(constants.NETWORK_STATE_LIST, networkstatejson)
	}
	if len(offlineIds) > 0 {
		result := db.Model(&entity.SystemInfo{}).Where("id IN ?", offlineIds).
			Updates(map[string]interface{}{"network_state": entity.OFFLINE})
		if result.Error != nil {
			logging.Error("批量更新主机状态失败: ", result.Error)
		} else {
			logging.Infof("成功将 %d 台主机标记为离线", result.RowsAffected)
		}
	}
	if len(logInfoList) > 0 {
		result := db.Create(&logInfoList)
		if result.Error != nil {
			logging.Error("批量创建日志失败: ", result.Error)
		}
	}
	logging.Info("----------定时检查主机掉线任务耗时：", time.Since(now).String())
}
